from khronos import Atomic, Delay

class Builder(Atomic):
    def __init__(self, callable, period, name=None, parent=None, priority=None):
        Atomic.__init__(self, name, parent, priority)
        self.__callable = callable
        self.__period = period
        self.__calls = 0
        
    def initializer(self):
        if not callable(self.__period):
            period = self.__period
            self.__period = lambda: period
        self.__calls = 0
        return Delay(self.get_rng().random() * self.__period())(activation=self.call)
        
    def call(self):
        self.__callable()
        self.__calls += 1
        return Delay(self.__period())(activation=self.call)
        
    def status(self):
        return "%d calls to %s" % (self.__calls, self.__callable.__name__)
        
